<template>
    <div class="account-manager-list">
        <!-- 顶部管理员展示组件 -->
        <AdminList title="管理员" :adminList="adminList" />

        <!-- 中间表格展示区域 -->
        <TableForm ref="tableFormRef" :initial-form="form" :total="total" @query="query" @reset="resetForm"
            @current-change="handleCurrentChange" @size-change="handleSizeChange">
            <!-- 上方条件查询区域 -->
            <template #form-items>
                <el-form-item>
                    <el-input v-trim class="common-input" v-model="form.LoginAccount" placeholder="请输入后台账号"
                        clearable></el-input>
                </el-form-item>

                <el-form-item>
                    <el-input v-trim class="common-input" v-model="form.UserName" placeholder="请输入用户名称"
                        clearable></el-input>
                </el-form-item>
            </template>

            <!-- 右侧添加账号按钮 -->
            <!-- 如果是超级管理员并且拥有当前的权限参数的时候可以添加权限 -->
            <template #add-button>
                <div @click="addAccount" class="add-account-button"
                    v-if="hasPermissionOrRole('AccountManagement.List', 1, 1)">
                    <img class="plus" src="@/assets/images/svg/plus.png" alt="" />
                    添加账号
                </div>
            </template>

            <!-- 中间表格信息展示区域 -->
            <template #table>
                <CommonTable :tableData="tableData" :max-height="630">
                    <el-table-column label="后台账号" prop="loginAccount"></el-table-column>
                    <el-table-column label="用户名称" prop="userName"></el-table-column>
                    <el-table-column label="权限组" prop="accessGroupName"></el-table-column>

                    <!-- 表单中的联系电话区域 -->
                    <el-table-column label="联系电话" prop="fullPhoneNo">
                        <template #default="{ row }">
                            {{ row.fullPhoneNo || '/' }}
                        </template>
                    </el-table-column>

                    <!-- 表单中的邮箱区域 -->
                    <el-table-column width="250" label="邮箱地址" prop="email">
                        <template #default="{ row }">
                            {{ row.email || '/' }}
                        </template>
                    </el-table-column>

                    <!-- 判断当前用户是否能启用当前账号 -->
                    <!-- 第一个1代表当前用户拥有传递的权限参数，第二个1代表当前用户是超级管理员,反之就是普通用户 -->
                    <el-table-column label="启用/禁用" v-if="userStore.userInfo.userRoleType == 1">
                        <template #default="{ row }">
                            <el-switch v-if="userStore.userInfo.isSuperAdminInit || row.loginAccount != 'SYSADMIN'"
                                :model-value="row.status === 1" @change="handleStatusChange(row)"
                                style="--el-switch-on-color: #2258f6; --el-switch-off-color: #d9d9d9" />
                        </template>
                    </el-table-column>

                    <!-- 创建人字段 -->
                    <el-table-column prop="createByName" label="创建人">
                        <template #default="{ row }">
                            {{ isAdminAccount(row.loginAccount) ? '/' : row.createByName }}
                        </template>
                    </el-table-column>

                    <!-- 创建时间字段 -->
                    <el-table-column width="250" label="创建时间">
                        <template #default="{ row }">
                            <span>
                                {{ dayjs(row.creationDate).format('YYYY-MM-DD HH:mm:ss') }}
                            </span>
                        </template>
                    </el-table-column>

                    <!-- 表单右侧权限操作区域 -->
                    <!-- 第一个1代表当前用户拥有传递的权限参数，第二个1代表当前用户是超级管理员,反之就是普通用户-->
                    <el-table-column fixed="right" label="操作" width="200"
                        v-if="hasPermissionOrRole('AccountManagement.List', 1, 1)">
                        <template #default="{ row }">
                            <div class="operation"
                                v-if="userStore.userInfo.isSuperAdminInit || row.loginAccount != 'SYSADMIN'">
                                <!-- 文字提示组件，包裹图标 这是编辑按钮 -->
                                <div v-if="hasPermissionOrRole('AccountManagement.Edit', 1, 1) && (!isAdminAccount(row.loginAccount) || userStore.userInfo.isSuperAdminInit)"
                                    class="detail detail-option" @click="goDetail(row.userId)">
                                    <span class="control-button">编辑</span>
                                </div>

                                <!-- 文字提示组件，包裹图标 这是重置按钮。拥有重置上方输入内容的功能-->
                                <div v-if="hasPermissionOrRole('AccountManagement.ResetPassword', 1, 1) && (!isAdminAccount(row.loginAccount) || userStore.userInfo.isSuperAdminInit)"
                                    class="detail detail-option" @click="handleReset(row.userId)">
                                    <span class="control-button">重置密码</span>
                                </div>

                                <!-- 文字提示组件，包裹图标 这是删除按钮 -->
                                <div v-if="hasPermissionOrRole('AccountManagement.Delete', 1, 1) && (!isAdminAccount(row.loginAccount) || userStore.userInfo.isSuperAdminInit)"
                                    class="detail error-status" @click="handleDelete(row.userId)">
                                    <span class="control-button delbtn">删除</span>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                </CommonTable>
            </template>
        </TableForm>

        <!--点击重置密码弹出框-->
        <NormalDialog :confirm-method="resetPsw" :visible="resetPswVisible" @close="closeResetDialog" title="重置密码"
            :icon="iconWarning" content="确认要重置密码吗"></NormalDialog>

        <!--重置密码成功的弹出框-->
        <el-dialog class="common-dialog" v-model="afterResetPswVisible" title="重置密码" width="300" align-center>
            <div class="content">
                <div class="tip">重置密码成功:</div>
                <div class="new-psw">&nbsp;{{ newPsw }}</div>
            </div>

            <template #footer>
                <el-button class="common-group-button confirm-button" type="primary"
                    @click="afterResetPswVisible = false">
                    确定
                </el-button>
            </template>
        </el-dialog>
    </div>

    <!-- 编辑以及新增的弹出框 -->
    <updateAccountDialog :userId="userId" :updateQuery="updateQuery" v-model:updateAccountVisible="updateAccountVisible"
        @updateQuery="updateQuery"></updateAccountDialog>
</template>

<script setup lang="ts">
import { h, onMounted, ref } from 'vue';
import dayjs from 'dayjs';
import iconWarning from '@/assets/imgs/warning_icon.png';
import CommonTable from '@/components/CommonTable/index.vue';
import NormalDialog from '@/components/NormalDialog.vue';
import TableForm from '@/components/TableForm/index.vue';
import usePermissionHasAccess from '@/hooks/permissionHasAccess';
import updateAccountDialog from './updateAccountDialog.vue';
import { successTips, errorTips } from '@/utils/utils';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { AccountPageType } from '@/type/accountType';
import { useUserStore } from '@/stores/user';
const userStore = useUserStore();
//获取管理员数据
import { getAdminList } from '@/apis/admin';

import { EnableAccount, addAccount, getAccountList, deleteAccount, resetPassword, EditAccount } from '@/apis/account';
import { AdminEnum } from '../../../enum/admin';

const { hasPermissionOrRole } = usePermissionHasAccess();

//编辑更细控制弹框的变量
const updateAccountVisible = ref(false);

interface FormType {
    LoginAccount: string;
    pageIndex: number;
    pageSize: number;
    UserName: string;
    SortField: string;
    SortOrder: string;
}

// 初始表单数据
const initialForm: FormType = {
    LoginAccount: '',
    UserName: '',
    pageIndex: 1,
    pageSize: 50,
    SortField: 'id',
    SortOrder: 'desc',
};

const form = ref<FormType>({ ...initialForm });
const total = ref(0);
const tableData: any = ref([]);
const resetPswVisible = ref(false);
const afterResetPswVisible = ref(false);
const newPsw = ref('');
const saveIdToResetPwd = ref(0);
const tableFormRef = ref();
const adminList = ref([]);

// 查询数据
const query = () => {
    getAccountList({
        loginAccount: form.value.LoginAccount,
        userName: form.value.UserName,
        pageIndex: form.value.pageIndex,
        pageSize: form.value.pageSize,
        sortField: form.value.SortField,
        sortOrder: form.value.SortOrder,
    }).then(res => {

        tableFormRef.value?.updateTotal(res.data.count);
        tableData.value = res.data.data;
    });
};

//启用禁用当前账号按钮功能
const handleStatusChange = (row: AccountPageType) => {
    // 当前状态是1（启用）时，要改为2（禁用）；当前状态是2（禁用）时，要改为1（启用）
    let isActive = row.status === 1 ? false : true;
    saveIdToResetPwd.value = row.userId;
    const message = isActive ? '确定要启用该账号吗？' : '确定要禁用该账号吗？';

    ElMessageBox.confirm(message, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        icon: h('img', {
            class: 'warning-icon',
            src: iconWarning,
        }),
    })
        .then(() => {
            EnableAccount({
                userId: row.userId,
                isActive: isActive,
            })
                .then(res => {
                    if (res.code === 1) {
                        successTips('操作成功');
                        // 更新当前行的状态：启用(1)或禁用(2)
                        row.status = isActive ? 1 : 2;
                        // 刷新列表数据
                        query();
                        fetchAdminList();
                    } else {
                        // 如果接口返回失败，恢复原来的状态
                        row.status = isActive ? 2 : 1;
                        errorTips('操作失败');
                    }
                })
                .catch(() => {
                    // 如果请求失败，恢复原来的状态
                    row.status = isActive ? 2 : 1;
                    errorTips('操作失败');
                });
        })
        .catch(() => {
            // 用户取消操作，恢复原来的状态
            row.status = isActive ? 2 : 1;
        });
};

//添加账户
const addAccount = () => {
    userId.value = 0; // 重置 userId 为 0 而不是空字符串
    updateAccountVisible.value = true;
};

//更新查询
const updateQuery = () => {
    query();
    fetchAdminList();
};

//检查是否是管理员账号（不区分大小写）
const isAdminAccount = account => {
    if (!account) return false;
    return account.toUpperCase() === 'SYSADMIN';
};

//获取账号管理页面的管理员数据
const fetchAdminList = async () => {
    try {
        const res = await getAdminList({ menuId: AdminEnum.ADMIN_ACCOUNT });
        // console.log('管理员列表数据:', res)
        if (res && res.data) {
            adminList.value = res.data;
        } else {
            adminList.value = [];
        }
    } catch (error) {
        adminList.value = [];
    }
};

//删除用户
const handleDelete = (userId: number) => {
    saveIdToResetPwd.value = userId;

    ElMessageBox.confirm('删除后数据无法恢复,确认要删除该账号吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        icon: h('img', {
            class: 'warning-icon',
            src: iconWarning,
        }),
    })
        .then(() => {
            deleteAccount({ userId: userId }).then(res => {

                if (res.code === 1) {
                    successTips('删除成功');
                    // 删除成功后刷新表格数据
                    query();
                    // 删除成功后刷新管理员列表数据
                    fetchAdminList();
                }
            });
        })
        .catch(() => { });
};

//重置密码触发事件
const handleReset = (userId: number) => {
    saveIdToResetPwd.value = userId;
    resetPswVisible.value = true;
};

//重置密码功能
const resetPsw = () => {
    resetPassword({ userId: saveIdToResetPwd.value })
        .then(res => {
            if (res.code === 1) {
                saveIdToResetPwd.value = 0;
                afterResetPswVisible.value = true;
                newPsw.value = res.data;
                resetPswVisible.value = false;
            }
        })
        .finally(() => {
            resetPswVisible.value = false;
        });
};

//关闭重置密码对话框
const closeResetDialog = (val: boolean) => {
    resetPswVisible.value = val;
};

// 重置表单
const resetForm = () => {
    form.value = { ...initialForm };
    query();
};

// 处理页码变化
const handleCurrentChange = (val: number) => {
    form.value.pageIndex = val;
    query();
};

// 处理每页条数变化
const handleSizeChange = (val: number) => {
    form.value.pageSize = val;
    form.value.pageIndex = 1; // 重置页码
    query();
};

const userId = ref(0);
const goDetail = editUserId => {
    userId.value = editUserId;
    updateAccountVisible.value = true;
};

//初始化时获取管理员列表
onMounted(() => {
    query();
    fetchAdminList();
});
</script>

<style scoped lang="scss">
.account-manager-list {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    background: #ffffff;
    padding: 15px 20px 0;

    .el-select {
        width: 192px;
    }

    .operation {
        display: flex;

        .detail,
        .reset-psw,
        .disable {
            cursor: pointer;
            margin-right: 15px;
        }
    }
}

.add-account-button {
    width: 108px;
    height: 32px;
    font-size: 14px;
    color: #fff;
    background: #2258f6;
    border-radius: 2px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;

    .plus {
        width: 16px;
        height: 16px;
        margin-right: 10px;
    }
}

.content {
    display: flex;
    align-items: center;
    margin: 12px 0;

    .new-psw {
        font-weight: bold;
    }
}

.control-button {
    font-family: Inter;
    font-size: 14px;
    font-weight: normal;
    color: #2258f6;
}

.delbtn {
    color: #e34d59;
}

.common-input {
    width: 190px;
    height: 32px;
}
</style>

<style>
.el-message-box__container {
    gap: 2px;
}
</style>
